package de.webtech.faceplace.pages;


import java.io.File;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.RadioContainer;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hibernate.Session;

import de.webtech.faceplace.entities.Person;

public class Settings {

	@Inject
	private Request request;
	
	public Person getPerson(){
		return (Person) request.getSession(true).getAttribute("user");
	}
	
	public String getFirstName(){
		return getPerson().firstName;
	}
	public String getLastName(){
		return getPerson().lastName;
	}
	
		//FIXME anständig setten usw.. 
      	
	
	
	  @Inject
	  private Session session;
	
		
	   @Property
       @Persist
       private String newFirstName;
       
       @Property
       @Persist
       private String newLastName;
       
       
       @Property
       @Persist
       private String newZip;
       
       @Property
       @Persist
       private String newPhoneNumber;
       
       @Property
       @Persist
       private String newCity;
       
       @CommitAfter
       public void onSubmitFromNewFirstNameForm(){
    	   getPerson().firstName=newFirstName;
    	   session.update(getPerson());
       }
       @CommitAfter
       public void onSubmitFromNewLastNameForm(){
    	   getPerson().lastName=newLastName;
    	   session.update(getPerson());
    	   
       }
       @CommitAfter
       public void onSubmitFromNewZipForm(){
    	   getPerson().zip=newZip;
    	   session.update(getPerson());
    	   
       }
       @CommitAfter
       public void onSubmitFromNewPhoneNumberForm(){
    	   getPerson().phone=newPhoneNumber;
    	   session.update(getPerson());
    	   
       }
       @CommitAfter
       public void onSubmitFromNewCityForm(){
    	   getPerson().city=newCity;
    	   session.update(getPerson());
       }
       
       @Property
       private UploadedFile file;
       
       @CommitAfter
       public void onSubmitFromNewPhotoForm(){
    	   File copied = new File("layout/profilepictures/"  + "uid" + getPerson().id + file.getFileName() );
    	  
           
           file.write(copied);
           getPerson().setPhotoSource("layout/profilepictures/" + "uid"+getPerson().id + file.getFileName());
           session.update(getPerson());
       }
       
       @Persist(PersistenceConstants.FLASH)
       @Property
       private String message;


       Object onUploadException(FileUploadException ex)
       {
           message = "Upload exception: " + ex.getMessage();

           return this;
       }
       

}
